<template>
  <div class="panel">
    <el-amap
      :center="center"
      :zoom="zoom"
      :map-style="mapStyle"
      :view-mode="viewMode"
      :rotation="rotation"
      :pitch="pitch"
    >
      <!-- 卫星图层 -->
      <el-amap-layer-satellite :visible="true" />

      <!-- 路线 -->
      <el-amap-polyline
        :path="routePath"
        :stroke-color="routeStyle.strokeColor"
        :stroke-weight="routeStyle.strokeWeight"
        :stroke-opacity="routeStyle.strokeOpacity"
        :stroke-style="routeStyle.strokeStyle"
        :line-join="routeStyle.lineJoin"
      />

      <!-- 标记点 -->
      <el-amap-marker
        v-for="point in tracePoints"
        :key="point.id"
        :position="point.position"
        :content="createMarkerContent(point)"
        :offset="[-30, -30]"
        @mouseover="handleMarkerMouseover(point)"
        @mouseout="handleMarkerMouseout"
      />

      <!-- 信息窗体 -->
      <el-amap-info-window
        v-if="currentInfo"
        :position="currentInfo.position"
        :visible="infoWindowVisible"
        :content="createInfoWindowContent(currentInfo)"
        :offset="[0, -30]"
        :auto-move="false"
        @close="closeInfoWindow"
      />
    </el-amap>

    <div class="overlay-info">
      <div class="info-title">农产品溯源地图</div>
      <div class="info-content">
        <div class="info-item">
          <span class="label">追溯节点：</span>
          <span class="value">{{ tracePoints.length }}个</span>
        </div>
        <div class="info-item">
          <span class="label">运输距离：</span>
          <span class="value">2,358公里</span>
        </div>
        <div class="info-item">
          <span class="label">预计时间：</span>
          <span class="value">48小时</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  ElAmap,
  ElAmapLayerSatellite,
  ElAmapMarker,
  ElAmapInfoWindow,
  ElAmapPolyline
} from '@vuemap/vue-amap'
import type { TraceRecord } from '@/types/traceability'
import { traceabilityApi } from '@/api/traceability'

interface TracePoint {
  id: number
  name: string
  position: [number, number]
  type: 'plant' | 'process' | 'storage' | 'delivery'
  time: string
  description: string
}

// 地图基础配置
const center = ref<[number, number]>([114.064719, 30.659462])
const zoom = ref(5)
const mapStyle = ref('amap://styles/dark')
const viewMode = ref('3D')
const rotation = ref(-15)
const pitch = ref(35)

// 路线样式
const routeStyle = {
  strokeColor: '#33FFD0',
  strokeWeight: 4,
  strokeOpacity: 0.8,
  strokeStyle: 'dashed' as const,
  lineJoin: 'round' as const
}

// 溯源点数据
const tracePoints = ref<TracePoint[]>([])

// 路线点
const routePath = computed(() => tracePoints.value.map(point => point.position))

// 信息窗口控制
const currentInfo = ref<TracePoint | null>(null)
const infoWindowVisible = ref(false)

// 获取溯源数据并转换为地图点
const fetchTraceData = async () => {
  try {
    console.log('开始获取溯源数据用于地图显示...')
    const response = await traceabilityApi.getAllTraceData()
    console.log('地图溯源数据API响应:', response)
    
    if (response.data.code === 200) {
      console.log('地图API返回成功，检查数据类型...')
      
      // 检查data是否为数组
      if (!Array.isArray(response.data.data)) {
        console.error('response.data.data不是数组:', {
          type: typeof response.data.data,
          value: response.data.data,
          response: response.data
        })
        console.log('使用模拟地图数据作为后备')
        useMockMapData()
        return
      }
      
      console.log('地图溯源数据获取成功，数据条数:', response.data.data.length)
      
      // 转换数据为地图点
      const mapPoints: TracePoint[] = []
      
      response.data.data.forEach((item: TraceRecord, index: number) => {
        console.log(`处理第${index + 1}条数据:`, {
          processName: item.processName,
          location: item.location,
          position: item.position,
          hasPosition: !!item.position
        })
        
        // 直接使用position字段
        let position: [number, number]
        
        if (item.position && Array.isArray(item.position) && item.position.length === 2) {
          // 使用后端返回的position字段
          position = item.position
          console.log(`✅ 使用后端position字段: [${position[0]}, ${position[1]}] for ${item.processName}`)
        } else {
          // 如果没有position信息，使用默认位置并添加偏移
          const basePosition: [number, number] = [114.064719, 30.659462]
          const offset = index * 0.1
          position = [basePosition[0] + offset, basePosition[1] + offset]
          console.log(`⚠️ 使用默认位置: [${position[0]}, ${position[1]}] for ${item.processName} (缺少position字段)`)
        }
        
        // 根据processType确定图标类型
        let type: TracePoint['type'] = 'process'
        switch (item.processType) {
          case 'planting':
            type = 'plant'
            break
          case 'processing':
            type = 'process'
            break
          case 'transport':
            type = 'delivery'
            break
          case 'storage':
            type = 'storage'
            break
          default:
            type = 'process'
        }
        
        mapPoints.push({
          id: index + 1,
          name: item.processName || `${item.processType}环节`,
          position: position,
          type: type,
          time: item.processTime,
          description: item.description || `${item.processName} - ${item.operator}`
        })
      })
      
      tracePoints.value = mapPoints
      console.log('地图点数据转换完成，点数:', mapPoints.length)
      
      if (mapPoints.length === 0) {
        console.warn('没有找到有效的地图点数据，使用模拟数据')
        useMockMapData()
      }
    } else {
      console.error('地图溯源数据API返回错误:', {
        code: response.data.code,
        message: response.data.message,
        data: response.data.data
      })
      console.log('使用模拟地图数据作为后备')
      useMockMapData()
    }
  } catch (error) {
    console.error('获取地图溯源数据失败:', {
      error: error,
      message: error instanceof Error ? error.message : '未知错误',
      stack: error instanceof Error ? error.stack : undefined,
      timestamp: new Date().toISOString()
    })
    console.log('使用模拟地图数据作为后备')
    useMockMapData()
  }
}

// 使用模拟地图数据
const useMockMapData = () => {
  console.log('加载模拟地图数据')
  tracePoints.value = [
    {
      id: 1,
      name: '种植基地',
      position: [126.642464, 45.756967],
      type: 'plant',
      time: '2024-03-01',
      description: '黑龙江农场种植基地'
    },
    {
      id: 2,
      name: '农产品检测',
      position: [125.324280, 43.886841],
      type: 'process',
      time: '2024-03-05',
      description: '吉林质检中心'
    },
    {
      id: 3,
      name: '初加工',
      position: [123.429096, 41.796767],
      type: 'process',
      time: '2024-03-10',
      description: '辽宁加工厂'
    },
    {
      id: 4,
      name: '区域仓储',
      position: [121.472644, 39.874143],
      type: 'storage',
      time: '2024-03-15',
      description: '大连物流中心'
    },
    {
      id: 5,
      name: '质量检测',
      position: [118.796877, 32.060255],
      type: 'process',
      time: '2024-03-17',
      description: '南京检测中心'
    },
    {
      id: 6,
      name: '中转仓储',
      position: [116.407526, 39.90403],
      type: 'storage',
      time: '2024-03-20',
      description: '北京仓储物流中心'
    },
    {
      id: 7,
      name: '加工包装',
      position: [114.058434, 22.543527],
      type: 'process',
      time: '2024-03-23',
      description: '深圳包装中心'
    },
    {
      id: 8,
      name: '配送中心',
      position: [113.280637, 23.125178],
      type: 'delivery',
      time: '2024-03-25',
      description: '广州配送中心'
    }
  ]
  console.log('模拟地图数据加载完成，点数:', tracePoints.value.length)
}

// 创建标记点内容
const createMarkerContent = (point: TracePoint) => {
  const iconMap = {
    plant: '🌾',
    process: '⚙️',
    storage: '🏢',
    delivery: '🚚'
  }

  const style = {
    'width': '50px',
    'height': '50px',
    'background': 'rgba(51, 255, 208, 0.2)',
    'border': '2px solid #33FFD0',
    'border-radius': '50%',
    'display': 'flex',
    'align-items': 'center',
    'justify-content': 'center',
    'font-size': '20px',
    'box-shadow': '0 0 20px rgba(51, 255, 208, 0.4)',
    'cursor': 'pointer',
    'transition': 'all 0.3s ease'
  }

  return `<div style="${Object.entries(style).map(([key, value]) => `${key}:${value}`).join(';')}">${iconMap[point.type]}</div>`
}

// 创建信息窗体内容
const createInfoWindowContent = (point: TracePoint) => {
  const typeMap = {
    plant: '种植基地',
    process: '加工环节',
    storage: '仓储物流',
    delivery: '配送中心'
  }

  return `
    <div class="info-window">
      <div class="info-window-title">${point.name}</div>
      <div class="info-window-item">类型：${typeMap[point.type]}</div>
      <div class="info-window-item">时间：${point.time}</div>
      <div class="info-window-item">描述：${point.description}</div>
    </div>
  `
}

// 处理标记点鼠标悬停
const handleMarkerMouseover = (point: TracePoint) => {
  currentInfo.value = point
  infoWindowVisible.value = true
}

// 处理标记点鼠标移出
const handleMarkerMouseout = () => {
  infoWindowVisible.value = false
}

// 关闭信息窗体
const closeInfoWindow = () => {
  infoWindowVisible.value = false
}

// 初始化
onMounted(async () => {
  await fetchTraceData()
})
</script>

<style scoped>
.panel {
  height: 100%;
  width: 100%;
  position: relative;
}

:deep(.amap-logo) {
  display: none !important;
}

:deep(.amap-copyright) {
  display: none !important;
}

.overlay-info {
  position: absolute;
  top: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.6);
  padding: 15px;
  border-radius: 8px;
  border: 1px solid rgba(51, 255, 208, 0.3);
  color: #fff;
  z-index: 1;
  backdrop-filter: blur(8px);
}

.info-title {
  color: #33FFD0;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item .label {
  color: #33FFD0;
}

.info-item .value {
  color: #fff;
}

:deep(.info-window) {
  padding: 15px;
  background: rgba(0, 0, 0, 0.8);
  border: 1px solid rgba(51, 255, 208, 0.3);
  border-radius: 8px;
  color: #fff;
  min-width: 200px;
}

:deep(.info-window-title) {
  color: #33FFD0;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

:deep(.info-window-item) {
  margin: 5px 0;
  font-size: 14px;
}

:deep(.amap-info-content) {
  background: transparent !important;
  border: none !important;
  padding: 0 !important;
}

:deep(.amap-info-sharp) {
  display: none !important;
}

:deep(.amap-info-close) {
  display: none !important;
}
</style> 